<template>
  <div class="preview-container">
    <div
      class="pageBox"
      :style="{
        opacity: autoGenerate ? 1 : 0,
        position: autoGenerate ? 'relative' : 'fixed',
        left: autoGenerate ? '0' : '-9999px',
      }"
    >
      <div class="report" id="report">
        <!-- 循环渲染每个公司的PDF -->
        <template
          v-for="(company, companyIndex) in pdfDataList"
          :key="companyIndex"
        >
          <!-- 第一页 -->
          <div class="pdf-page">
            <div class="pdfBox">
              <!-- 添加水印 -->
              <div class="sy">
                <img src="@/assets/sy.png" alt="" />
              </div>
              <div class="titleBox">
                <img src="@/assets/logo.png" alt="" />
                <div class="text">
                  <p>天津巨人检测有限责任公司</p>
                  <p>食品快速检测数据单(定性)</p>
                </div>
              </div>
              <div class="tbox">
                <div class="sbox sbox1">
                  <div class="pageTitle">
                    <strong>样品信息</strong>
                    <p>数据单号：{{ company.code }}</p>
                  </div>
                  <table>
                    <tr>
                      <td><strong>受检单位</strong></td>
                      <td colspan="3">{{ company.unit_name }}</td>
                    </tr>
                    <tr>
                      <td><strong>受检单位地址</strong></td>
                      <td colspan="3">{{ company.address }}</td>
                    </tr>
                    <tr>
                      <td><strong>联系人</strong></td>
                      <td>{{ company.name || '/' }}</td>
                      <td><strong>联系电话</strong></td>
                      <td>{{ company.phone || '/' }}</td>
                    </tr>
                    <tr>
                      <td><strong>样品量</strong></td>
                      <td>{{ company.sample_num || '/' }}</td>
                      <td><strong>样品类别</strong></td>
                      <td>{{ company.sample_type || '/' }}</td>
                    </tr>
                    <tr>
                      <td><strong>抽样日期</strong></td>
                      <td>{{ company.smple_time_text || '/' }}</td>
                      <td><strong>检测日期</strong></td>
                      <td>{{ company.detection_time_text || '/' }}</td>
                    </tr>
                  </table>
                </div>

                <div class="sbox sbox2">
                  <div class="pageTitle">
                    <strong>检测结果（定性）</strong>
                  </div>
                  <table>
                    <thead>
                      <tr>
                        <th style="width: 60px">样品名称</th>
                        <th style="width: 100px">样品编号</th>
                        <th style="width: 100px">检测项目</th>
                        <th style="width: 60px">检测结果</th>
                        <th style="width: 80px">检测方法</th>
                        <th style="width: 60px">检出限</th>
                        <th style="width: 60px">单位</th>
                        <th style="width: 60px">备注</th>
                      </tr>
                    </thead>
                    <tr
                      v-for="(item, index) in getFirstPageData(
                        company.detection_json,
                        company.remark
                      )"
                      :key="index"
                    >
                      <td>{{ item.sample_name || '/' }}</td>
                      <td>{{ item.code || '/' }}</td>
                      <td>{{ item.project_name || '/' }}</td>
                      <td>{{ item.result || '/' }}</td>
                      <td>{{ item.method_name || '/' }}</td>
                      <td>{{ item.outmsg || '/' }}</td>
                      <td>{{ item.unitmsg || '/' }}</td>
                      <td>{{ item.remark || '/' }}</td>
                    </tr>
                  </table>
                  <div
                    class="tip"
                    v-if="
                      company.detection_json.length <= isNum(company.remark) &&
                      company.remark
                    "
                  >
                    <span>备注</span>
                    <p>{{ company.remark || '/' }}</p>
                  </div>
                </div>

                <template
                  v-if="company.detection_json.length <= isNum(company.remark)"
                >
                  <div class="qianzi">
                    <img src="@/assets/zhang.png" class="img1" alt="" />
                    <div class="line">
                      <p>编制：{{ company.createuser }}</p>
                      <p>审核：{{ company.admin.username }}</p>
                    </div>
                    <div class="line">
                      <p>日期： {{ company.detection_time_text || '/' }}</p>
                      <p></p>
                    </div>
                    <img :src="company.ewm_url" alt="" class="img2" />
                  </div>

                  <div class="pageEnd">
                    <div class="title">*** 报告结束 ***</div>
                    <p>
                      1.报告无快速检测专用章或经涂改以及复印报告未加盖红色快速检测专用章均视作无效;
                    </p>
                    <p>2.未经本公司批准，不得部分复制本报告;</p>
                    <p>3.样品信息由客户提供，本报告检测结果仅对受检样品负责;</p>
                    <p>4.不得擅自使用检测结果进行不当宣传;</p>
                    <p>
                      5.如果对检测结果有异议，请于收到报告之日起4小时内提出，逾期不予受理;
                    </p>
                    <p>
                      6.本报告中的全部检测项目未取得资质认定，仅供科研、教学、企业内部质量控制、企业产品研发等目的用
                    </p>
                  </div>
                </template>
              </div>

              <div class="pageBottom">
                <img src="@/assets/bottom.png" alt="" />
              </div>
            </div>
          </div>

          <!-- 动态生成后续页面 -->
          <template
            v-if="company.detection_json.length > isNum(company.remark)"
          >
            <template
              v-for="(chunk, pageIndex) in getRemainingPages(
                company.detection_json,
                company.remark
              )"
              :key="pageIndex"
            >
              <div class="pdf-page">
                <div class="pdfBox">
                  <!-- 添加水印 -->
                  <div class="sy">
                    <img src="@/assets/sy.png" alt="" />
                  </div>
                  <div class="titleBox">
                    <img src="@/assets/logo.png" alt="" />
                    <div class="text">
                      <p>天津巨人检测有限责任公司</p>
                      <p>食品快速检测数据单(定性)</p>
                    </div>
                  </div>
                  <div class="tbox">
                    <!-- 显示数据表格（如果这页有数据） -->
                    <div
                      class="sbox sbox2"
                      style="margin-top: 0"
                      v-if="
                        chunk &&
                        chunk.length > 0 &&
                        company.detection_json.length > 13
                      "
                    >
                      <table style="margin-top: 0">
                        <thead>
                          <tr>
                            <th style="width: 60px">样品名称</th>
                            <th style="width: 100px">样品编号</th>
                            <th style="width: 100px">检测项目</th>
                            <th style="width: 60px">检测结果</th>
                            <th style="width: 80px">检测方法</th>
                            <th style="width: 60px">检出限</th>
                            <th style="width: 60px">单位</th>
                            <th style="width: 60px">备注</th>
                          </tr>
                        </thead>
                        <tr v-for="(item, index) in chunk" :key="index">
                          <td>{{ item.sample_name || '/' }}</td>
                          <td>{{ item.code || '/' }}</td>
                          <td>{{ item.project_name || '/' }}</td>
                          <td>{{ item.result || '/' }}</td>
                          <td>{{ item.method_name || '/' }}</td>
                          <td>{{ item.outmsg || '/' }}</td>
                          <td>{{ item.unitmsg || '/' }}</td>
                          <td>{{ item.remark || '/' }}</td>
                        </tr>
                      </table>
                    </div>

                    <!-- 显示备注 -->
                    <template
                      v-if="
                        isLastPage(
                          pageIndex,
                          company.detection_json,
                          company.remark
                        ) && company.remark
                      "
                    >
                      <div class="tip">
                        <span>备注</span>
                        <p>{{ company.remark || '/' }}</p>
                      </div>
                    </template>

                    <!-- 显示签名信息 -->
                    <template
                      v-if="
                        isLastPage(
                          pageIndex,
                          company.detection_json,
                          company.remark
                        )
                      "
                    >
                      <div class="qianzi">
                        <img src="@/assets/zhang.png" class="img1" alt="" />
                        <div class="line">
                          <p>编制：{{ company.createuser }}</p>
                          <p>审核：{{ company.admin.username }}</p>
                        </div>
                        <div class="line">
                          <p>日期： {{ company.detection_time_text || '/' }}</p>
                          <p></p>
                        </div>
                        <img :src="company.ewm_url" alt="" class="img2" />
                      </div>

                      <div class="pageEnd">
                        <div class="title">*** 报告结束 ***</div>
                        <p>
                          1.报告无快速检测专用章或经涂改以及复印报告未加盖红色快速检测专用章均视作无效;
                        </p>
                        <p>2.未经本公司批准，不得部分复制本报告;</p>
                        <p>
                          3.样品信息由客户提供，本报告检测结果仅对受检样品负责;
                        </p>
                        <p>4.不得擅自使用检测结果进行不当宣传;</p>
                        <p>
                          5.如果对检测结果有异议，请于收到报告之日起4小时内提出，逾期不予受理;
                        </p>
                        <p>
                          6.本报告中的全部检测项目未取得资质认定，仅供科研、教学、企业内部质量控制、企业产品研发等目的用
                        </p>
                      </div>
                    </template>
                  </div>

                  <div class="pageBottom">
                    <img src="@/assets/bottom.png" alt="" />
                  </div>
                </div>
              </div>
            </template>
          </template>
        </template>
      </div>
    </div>
    <el-button
      type="primary"
      class="submit"
      :disabled="isGenerating"
      :loading="loading"
      @click="downReport"
      v-if="autoGenerate"
    >
      {{ isGenerating ? '请稍等' : loading ? '导出中...' : '导出' }}
    </el-button>
  </div>
</template>

<script setup>
  import {
    onMounted,
    reactive,
    ref,
    computed,
    nextTick,
    onUnmounted,
  } from 'vue';
  import { useRoute } from 'vue-router';
  import htmlToPdf from '@/utils/htmlToPDF';
  import axios from 'axios';

  const route = useRoute();
  const loading = ref(false);
  const autoGenerate = ref(false);
  const dataLoaded = ref(false);
  const pdfurl = ref(false);
  const pdfDataList = ref([]);
  const isGenerating = ref(false);
  let pollingInterval = null;
  // 每页显示的数据条数
  const FIRST_PAGE_ITEMS = 14; // 第一页最多显示13条
  const OTHER_PAGE_ITEMS = 19; // 中间页显示19条
  const LAST_PAGE_THRESHOLD = 12; // 最后一页数据超过这个数，备注就要和签名一起放到新页

  // 轮询检查PDF状态
  const checkPdfStatus = async id => {
    try {
      const response = await axios.get(
        `https://g.gdimall.com/api/index/getInfo?id=${id}`
      );
      if (response.data.data.pdfurl) {
        pdfurl.value = response.data.data.pdfurl;
        isGenerating.value = false;
        if (pollingInterval) {
          clearInterval(pollingInterval);
          pollingInterval = null;
        }
      }
    } catch (error) {
      console.error('获取数据失败:', error);
    }
  };

  const downReport = async () => {
    if (!isGenerating.value) {
      const url = pdfurl.value;
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', `食品快速检测数据单(定性).pdf`);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    }
  };

  const fetchData = async id => {
    try {
      const response = await axios.get(
        `https://g.gdimall.com/api/index/getInfo?id=${id}`
      );
      pdfDataList.value = response.data.data.info;
      pdfurl.value = response.data.data.pdfurl;
      dataLoaded.value = true; 

      // 如果pdfurl为空，开始轮询
      if (!pdfurl.value && route.query.show) {
        isGenerating.value = true;
        pollingInterval = setInterval(() => checkPdfStatus(id), 2000);
      }

      await nextTick();

      setTimeout(async () => {
        if (!route.query.show) {
          const pdfBlob = await printReport();
          if (pdfBlob) {
            await uploadPDF(pdfBlob, id);
          }
        }
      }, 1000);
    } catch (error) {
      console.error('获取数据失败:', error);
    }
  };

  // 上传PDF文件到服务器
  const uploadPDF = async (pdfBlob, id) => {
    try {
      const formData = new FormData();
      formData.append('file', pdfBlob, `report_${id}.pdf`);
      formData.append('id', id);

      const response = await axios.post(
        'https://g.gdimall.com/api/index/uploadPdf',
        formData,
        {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        }
      );

      if (response.data.code === 200) {
        console.log('PDF上传成功');
        // 上传成功后关闭页面
        window.close();
      } else {
        console.error('PDF上传失败:', response.data.msg);
      }
    } catch (error) {
      console.error('PDF上传出错:', error);
    }
  };

  const isNum = remark => {
    return remark ? 6 : 7;
  };

  // 获取第一页数据的函数
  const getFirstPageData = (data, remark) => {
    // 如果总数据大于13条，显示13条
    if (data.length > FIRST_PAGE_ITEMS) {
      return data.slice(0, FIRST_PAGE_ITEMS);
    }
    // 如果总数据大于7条但小于等于13条，显示全部
    if (data.length > isNum(remark)) {
      return data;
    }
    // 如果总数据小于等于7条，全部显示
    return data;
  };

  // 获取剩余页面数据的函数
  const getRemainingPages = (data, remark) => {
    let remainingData;

    // 如果总数据大于13条，获取剩余数据
    if (data.length > FIRST_PAGE_ITEMS) {
      remainingData = data.slice(FIRST_PAGE_ITEMS);
    }
    // 如果总数据大于7条但小于等于13条，不需要数据但需要一个空页放签名
    else if (data.length > isNum(remark)) {
      remainingData = [];
    }
    // 如果总数据小于等于7条，不需要额外页面
    else {
      return [];
    }

    const pages = [];

    // 如果有剩余数据（即大于13条的情况）
    if (remainingData.length > 0) {
      // 计算需要多少个数据页
      for (let i = 0; i < remainingData.length; i += OTHER_PAGE_ITEMS) {
        const pageData = remainingData.slice(i, i + OTHER_PAGE_ITEMS);
        pages.push(pageData);
      }

      // 如果最后一页数据超过阈值，添加新页放备注和签名
      if (
        pages.length > 0 &&
        pages[pages.length - 1].length > LAST_PAGE_THRESHOLD
      ) {
        pages.push([]);
      }
    }
    // 7-13条数据的情况，添加一个空页放签名
    else if (data.length > isNum(remark) && data.length <= FIRST_PAGE_ITEMS) {
      pages.push([]);
    }

    return pages;
  };

  const isLastPage = (pageIndex, data, remark) => {
    const remainingPages = getRemainingPages(data, remark);
    return pageIndex === remainingPages.length - 1;
  };

  const printReport = async () => {
    if (!dataLoaded.value) {
      console.error('数据还未加载完成');
      return null;
    }

    loading.value = true;
    try {
      const pdfBlob = await htmlToPdf.getPdf('周期报告', '#report');
      // 根据show参数决定是下载还是上传
      const show = route.query.show;
      return pdfBlob;
    } catch (error) {
      console.error('导出失败:', error);
      return null;
    } finally {
      loading.value = false;
    }
  };

  // 添加缩放函数
  const setScale = () => {
    const report = document.querySelector('#report');
    if (report) {
      const screenWidth = window.innerWidth;
      const reportWidth = 210 * 3.78; // 210mm 转换为像素（1mm ≈ 3.78px）
      if (screenWidth < reportWidth) {
        const scale = screenWidth / reportWidth;
        report.style.transform = `scale(${scale})`;
        report.style.transformOrigin = 'top left';
        // 调整容器高度以适应缩放后的内容
        const reportHeight = report.offsetHeight * scale;
        report.parentElement.style.height = `${reportHeight}px`;
      } else {
        report.style.transform = 'none';
        report.style.transformOrigin = 'top center';
        report.parentElement.style.height = 'auto';
      }
    }
  };

  onMounted(() => {
    if (route.query.show) {
      // 初始设置
      setScale();

      // 监听窗口大小变化
      window.addEventListener('resize', setScale);
    }
  });

  onUnmounted(() => {
    window.removeEventListener('resize', setScale);
    // Clear polling interval if it exists
    if (pollingInterval) {
      clearInterval(pollingInterval);
      pollingInterval = null;
    }
  });

  onMounted(async () => {
    // 检查URL参数
    const id = route.query.id;
    const show = route.query.show;
    if (id) {
      if (show) {
        autoGenerate.value = true;
      }
      await fetchData(id);
    }
  });
</script>

<style scoped lang="scss">
  .preview-container {
    width: 100%;

    @media screen and (max-width: 793px) {
      padding: 0;
    }
  }

  .pageBox {
    width: 210mm;
    margin: 0 auto;

    @media screen and (max-width: 793px) {
      width: 100%;
    }
  }

  #report {
    width: 210mm;
    background: white;
    margin: 0 auto;

    @media screen and (max-width: 793px) {
      width: 100%;
    }
  }

  .pdf-page {
    width: 210mm;
    min-height: 297mm;
    margin: 0;
    padding: 0;
    position: relative;
    background: white;
    page-break-after: always;

    @media screen and (max-width: 793px) {
      width: 100%;
    }

    &:last-child {
      page-break-after: avoid;
    }
  }

  .pdfBox {
    width: 210mm;
    min-height: 297mm;
    padding: 0;
    margin: 0;
    position: relative;
    background: white;
    box-sizing: border-box;

    @media screen and (max-width: 793px) {
      width: 100%;
    }

    .sy {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      pointer-events: none;
      z-index: 3;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .tbox {
      position: relative;
      z-index: 2;
      padding: 30px;
      padding-top: 7px;
      box-sizing: border-box;
      width: 100%;
    }

    .sbox1,
    .sbox2 {
      table {
        min-width: 100%;

        td,
        th {
          padding: 0px 5px;

          @media screen and (min-width: 768px) {
            padding: 0 5px;
          }
        }
      }
    }

    .titleBox {
      .text {
        width: 90%;

        @media screen and (min-width: 768px) {
          width: 65%;
        }

        p {
          font-size: 14px;

          @media screen and (min-width: 768px) {
            font-size: 18px;
          }
        }
      }
    }
  }

  .submit {
    position: fixed;
    left: 50%;
    bottom: 20px;
    transform: translateX(-50%);
    z-index: 999;
    width: 140px;
    font-size: 20px;
    height: 45px;
  }

  .infoBox {
    display: flex;
    justify-content: space-between;
    width: 1000px;
  }

  .pageEnd {
    text-align: center;
    margin-top: 30px;
    .title {
      font-size: 15px;
      margin-bottom: 10px;
      color: #333;
    }
    p {
      font-size: 14px;
      color: #999999;
      line-height: 24px;
    }
  }

  .qianzi {
    margin-top: 30px;
    position: relative;
    .img1 {
      position: absolute;
      width: 160px;
      top: -40px;
      left: 100px;
    }
    .img2 {
      position: absolute;
      width: 130px;
      top: -30px;
      right: 30px;
    }
    .line {
      display: flex;
      justify-content: space-around;
      margin-bottom: 30px;
      p {
        width: 30%;
        font-size: 16px;
        color: #333333;
      }
    }
  }

  .pdfBox {
    width: 210mm;
    min-height: 297mm;
    padding: 0;
    margin: 0;
    position: relative;
    background: white;
    box-sizing: border-box;

    .tbox {
      padding: 30px;
      padding-top: 7px;
      box-sizing: border-box;
      width: 100%;
    }
    .pageBottom {
      position: absolute;
      bottom: 20px;
      left: 0;
      width: 100%;
      text-align: center;
      img {
        width: 100%;
        display: block;
        margin: 0 auto;
      }
    }
    .tip {
      margin-top: 10px;
      font-size: 14px;
      span {
        display: block;
        color: #999999;
      }
      p {
        color: #333333;
        margin-top: 10px;
      }
    }
    .sbox {
      background: #fff;
      width: 100%;
      box-sizing: border-box;
    }
    .sbox1,
    .sbox2 {
      table {
        width: 100%;
      }
    }

    .sbox2 {
      margin-top: 20px;
      table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 10px;
        tr {
          height: 45px;
          &:nth-child(even) {
            background: #ebf1fe;
          }
          td {
            text-align: center;
            border-bottom: 1px solid #d3daf0;
            font-size: 14px;
            color: #333333;
          }
        }
        thead {
          height: 30px;
          tr {
            background: #fff !important;
          }
          th {
            font-size: 14px;
            color: #2544a1;
            border-bottom: 1px solid #8aa3eb;
            border-top: 1px solid #8aa3eb;
          }
        }
      }
    }
    .sbox1 {
      table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 10px;
        border-top: 1px solid #8aa3eb;
        border-right: 1px solid #8aa3eb;
        tr {
          height: 30px;
          td {
            font-size: 14px;
            color: #333;
            border-bottom: 1px solid #8aa3eb;
            border-left: 1px solid #8aa3eb;
            padding: 0 20px;
            text-align: center;
            strong {
              font-size: 14px;
              color: #3250a7;
            }
          }
        }
      }
    }
    .pageTitle {
      display: flex;
      justify-content: space-between;
      align-items: center;
      p {
        font-size: 14px;
        color: #54616c;
      }
      strong {
        display: block;
        font-size: 16px;
        font-weight: normal;
        line-height: 28px;
        position: relative;
        padding-left: 30px;
        &::before {
          content: '';
          position: absolute;
          width: 10px;
          height: 24px;
          background: #4e73df;
          top: 0px;
          left: 0px;
        }
        &::after {
          content: '';
          position: absolute;
          width: 4px;
          height: 24px;
          background: #4e73df;
          top: 0px;
          left: 14px;
        }
      }
    }

    .titleBox {
      text-align: center;
      height: 115px;
      padding-top: 20px;
      margin-bottom: 20px;
      box-sizing: border-box;
      position: relative;
      background: #4e73df;
      h1 {
        font-size: 24px;
        font-weight: bold;
        height: 70px;
        color: #fff;
      }
      .text {
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 55%;
        padding: 0 20px;
        margin: 0 auto;
        margin-top: 5px;
        box-sizing: border-box;
        p {
          font-size: 16px;
          color: #dce3f9;
        }
      }
    }
  }
</style>
